package etnorservice.etnor_service.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/03/19/12:16
 **/
@Slf4j
public class ImageCompressUtil {

    public static void compressImage(Path sourcePath, Path targetPath, float quality) throws IOException {
        try {
            BufferedImage sourceImage = ImageIO.read(sourcePath.toFile());

            // 创建一个新的RGB图像
            BufferedImage newImage = new BufferedImage(
                    sourceImage.getWidth(),
                    sourceImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB
            );

            // 绘制原始图像到新图像
            newImage.createGraphics().drawImage(sourceImage, 0, 0, null);

            // 写入压缩后的图像
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = writers.next();

            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality); // 0.0f - 1.0f

            try (ImageOutputStream output = ImageIO.createImageOutputStream(targetPath.toFile())) {
                writer.setOutput(output);
                writer.write(null, new IIOImage(newImage, null, null), param);
            }

            writer.dispose();
            log.info("图片压缩完成: {}", targetPath);
        } catch (Exception e) {
            log.error("图片压缩失败: {}", e.getMessage());
            throw new IOException("图片压缩失败", e);
        }
    }
}
